package dcq;

import org.gdal.gdal.gdal;
import org.gdal.ogr.*;
import org.gdal.osr.SpatialReference;

public class GDALShp {

    static {

        /*   准备工作   */
        gdal.AllRegister();
        //注册所有驱动
        ogr.RegisterAll();
        //支持中文路径
        gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES");
        //属性表支持中文 pszValue设为“”，可以兼容读取中文 GBK、UTF-8不乱码
        gdal.SetConfigOption("SHAPE_ENCODING", "");
    }

    /**
     * @param strVectorFile .shp文件绝对路径
     * @return
     */
    public String opeanShp(String strVectorFile) {

        //获取驱动
        String driverName = "ESRI Shapefile";
        Driver driver = ogr.GetDriverByName(driverName);
        if (driver == null) {
            throw new RuntimeException(driverName + " 驱动不可用！\n");
        }

        //获取数据源
        DataSource dataSource = ogr.Open(strVectorFile, 0);
        if (dataSource == null) {
            throw new RuntimeException("打开文件【" + strVectorFile + "】失败！");
        }

        String lyrgeojson = "";

        // 获取该数据源中的图层个数，如果小于1返回错误，shp只有一个图层，mdb会有多个
        int layerCount = dataSource.GetLayerCount();
        System.out.println("图层数 = " + layerCount);
        if (layerCount < 1) {
            System.err.println("异常：没有图层。");
            return "";
        }

        //shp只有一个图层
        for (int i = 0; i < dataSource.GetLayerCount(); i++) {

            //获取图层
            Layer layer = dataSource.GetLayer(i);
            if (layer != null) {
                // 获取shp文件四角坐标范围
                double[] extent = layer.GetExtent(true);
                System.out.println("extent is ：" + extent[0] + ", " + extent[1] + ", " + extent[2] + ", " + extent[3]);
                // 获取图层名
                System.out.println("图层名" + "：" + layer.GetName());
            }

            //获取坐标系
            long swigCPtr = Layer.getCPtr(layer);
            SpatialReference spatialReference = layer.GetSpatialRef();
            if (spatialReference != null) {
                String wkt = spatialReference.ExportToWkt();
                System.out.println("坐标系统为:");

                spatialReference.GetAuthorityCode("GEOGCS");
                String epsgCode = spatialReference.GetAuthorityCode(null);
                System.out.println(wkt);
                System.out.println(epsgCode);

            } else {
                System.out.println("图层没有定义空间参考");
            }

            //获取要素信息
            long feaCount = layer.GetFeatureCount();
            System.out.println("该图层总共的要素数量：" + feaCount);

            do {//获取图层下的要素
                String feaGeoJson;
                //获取一个要素
                Feature feature = layer.GetNextFeature();
              /*
                  不用 layer.GetFeature(long fid) 遍历，
                  因为shp的fid从0~ （feaCount-1），
                  gdb的fid从1~ （feaCount），
               */
                if (feature == null) {
                    break;
                }
                System.out.println("fid内容：" + feature.GetFID() + "\n");
                //获取要素属性
                int feildCount = feature.GetFieldCount();
                for (int p = 0; p < feildCount; p++) {
                    FieldDefn fieldDefn = feature.GetFieldDefnRef(p);
                    System.out.println(fieldDefn.GetName() + ","
                            + fieldDefn.GetFieldType() + ","
                            + fieldDefn.GetTypeName() + ","
                            + GDALHelper.getProperty(feature, p)
                    );
                }
                //获取要素图形
                Geometry geometry = feature.GetGeometryRef();
                feaGeoJson = geometry.ExportToJson(); //也可以ExportToWkt、 ExportToWkb、gml等等
                System.out.println("图形内容：" + feaGeoJson + "\n");

            } while (true);
        }


        dataSource.delete();
        gdal.GDALDestroyDriverManager();
        return lyrgeojson;
    }

    public static void main(String[] args) {
        GDALShp shp = new GDALShp();
//        String strVectorFile = "E:\\workproject_0\\gdal\\my-gdal-java-demo\\my-gdal-java-demo\\gisdata\\JJHXZJ84.shp";
        String strVectorFile = "E:\\workproject_0\\gdal\\my-gdal-java-demo\\my-gdal-java-demo\\gisdata\\pg2shp.shp";
        String info = shp.opeanShp(strVectorFile);
        System.out.println(info);

    }
}
